import React, { useEffect, useRef, useState } from 'react';
import { message, Spin } from 'antd';
import moment from 'moment';
import { connect } from 'umi';
import { useSetState } from 'ahooks';
import { TRDefault } from '@/components/index.js';
import { getTreeByCodes } from '@/utils/index.js';
import { HttpCode } from '#/utils/contacts.js';
import Strategy from './Strategy';
import DeclareToPerform from './DeclareToPerform';
import DeviationAnalysis from './DeviationAnalysis';
import { Header, Steps } from './components';
import { queryMarketList, postQueryIssuePlanList, postShowAiStrategy } from './service';
import type { IProps, IFormValue, IDealElementOptions, IQueryIssuePlanListDataType } from './type';
import { IStepsType, IExecuteStatusType, IResetType } from './type';
import { stepsOptions, specialProvinceValue } from './dictionary';
import styles from './index.less';
import ShorttermForecastingRedesignV2 from '../ShorttermForecastingRedesignV2/index.jsx';

const ShorttermForecastingRedesign = (props: IProps) => {
  const { buttonPermissions, menuCode } = props;
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<boolean>(false);
  const [activeStep, setActiveStep] = useState<IStepsType>(IStepsType.STRATEGY);
  const [formValue, setFormValue] = useSetState<IFormValue>({});
  const [activeKey, setActiveKey] = useState<any>('1');
  const [saveButtonDisabled, setSaveButtonDisabled] = useState<boolean>(false); // 是否仅用保存
  const [provinceOptions, setProvinceOptions] = useState<IDealElementOptions[]>([]); // 省份数据
  const [queryIssuePlanListData, setQueryIssuePlanListData] = useState<any>();
  const [aiStrategyData, setAiStrategyData] = useState<any>();
  const strategyRef: any = useRef(null);

  // 搜索数据
  const onSearch = async (params: IFormValue) => {
    setQueryIssuePlanListData({});
    setAiStrategyData([]);
    setFormValue(params);
    const _diff = moment()
      .startOf('days')
      .diff(moment(params?.calendarDate).startOf('days'), 'days');
    const { provinceName, stationName, quantityQuotation, calendarDate, ...arg }: any = params;

    const isArray = calendarDate instanceof Array;
    const param = {
      ...arg,
      calendarDate: isArray ? calendarDate[0] : calendarDate,
    };
    const [res1, res2] = await Promise.all([
      postQueryIssuePlanList(param),
      postShowAiStrategy(arg.stationId),
    ]);
    const _disabled =
      (res1?.data || []).length > 0
        ? res1?.data?.find((item: IQueryIssuePlanListDataType) => {
            return item.executeStatus !== IExecuteStatusType.EXECUTED;
          })
          ? false
          : true
        : false;
    const _saveButtonDisabled = _diff >= 0 ? true : _disabled;
    const _activeStep = _saveButtonDisabled ? IStepsType.DECLARE_TO_PERFORM : IStepsType.STRATEGY;

    setQueryIssuePlanListData(res1);
    if (res2?.statusCode === HttpCode.SUCCESS) {
      setAiStrategyData(res2.data);
    } else {
      message.error(res2.message);
    }
    setActiveStep(_activeStep);
    setSaveButtonDisabled(_saveButtonDisabled);
    if (_activeStep === activeStep) {
      setActiveKey(moment().valueOf());
    }
  };
  const defaultRequest = async (data: any) => {
    const { marketId, provinceId, stationName, provinceName, children } = data[0];
    const _params: any = {
      quantityQuotation: 1,
      calendarDate: moment()
        // .add(provinceId === specialProvinceValue ? 2 : 1, 'day')
        .add(1, 'day')
        .format('YYYY-MM-DD'),
      marketId,
      provinceName,
      provinceId,
      stationName,
      stationId: children?.[0]?.stationId,
      saveType: 1,
    };
    await onSearch(_params);
  };

  // 获取省份/交易单元数据
  const getProvinceData = async () => {
    setLoading(true);
    const res = await queryMarketList(menuCode);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const { treeOptions } = getTreeByCodes(['market', 'station'], res.json);
      setProvinceOptions(treeOptions);
      await defaultRequest(treeOptions);
    } else {
      setError(true);
    }
    setLoading(false);
  };

  // 切换步骤条
  const onChangeSteps = (e: IStepsType) => {
    setActiveStep(e);
  };

  const strategyOnReset = () => {
    strategyRef?.current?.onReset?.(IResetType.RESET);
  };

  useEffect(() => {
    getProvinceData();
  }, []);

  return (
    <div className={styles.container}>
      {loading ? (
        <Spin spinning />
      ) : error ? (
        <TRDefault type={'error'} message={'系统异常'} />
      ) : (
        <div className={styles.container}>
          <div className={styles.header}>
            <Header
              strategyOnReset={strategyOnReset}
              values={formValue}
              defaultRequest={defaultRequest}
              provinceOptions={provinceOptions}
              onSearch={onSearch}
            />
          </div>
          {/* 山西 甘肃重构界面 */}
          {formValue.marketId === 'PHBSX' || formValue.marketId === 'PXBGS' ? (
            <ShorttermForecastingRedesignV2
              searchParams={formValue}
              activeStep={activeStep}
              setActiveStep={setActiveStep}
            />
          ) : (
            <div className={styles.content}>
              <div className={styles.steps}>
                <Steps options={stepsOptions} onChange={onChangeSteps} value={activeStep} />
              </div>
              {activeStep === IStepsType.STRATEGY && (
                <div className={styles.stepsContent}>
                  <Strategy
                    ref={strategyRef}
                    formValue={formValue}
                    activeStep={activeStep}
                    activeKey={activeKey}
                    menuCode={menuCode}
                    saveButtonDisabled={saveButtonDisabled}
                    buttonPermissions={buttonPermissions}
                    aiStrategyData={aiStrategyData}
                    power={provinceOptions}
                  />
                </div>
              )}
              {activeStep === IStepsType.DECLARE_TO_PERFORM && (
                <div className={styles.stepsContent}>
                  <DeclareToPerform
                    activeStep={activeStep}
                    formValue={formValue}
                    activeKey={activeKey}
                    buttonPermissions={buttonPermissions}
                    queryIssuePlanListData={queryIssuePlanListData}
                  />
                </div>
              )}
              {activeStep === IStepsType.DEVIATION_ANALYSIS && (
                <div className={styles.stepsContent}>
                  <DeviationAnalysis formValue={formValue} activeKey={activeKey} />
                </div>
              )}
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default connect(({ shorttermForecastingRedesign, global }: any) => ({
  global,
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
  shorttermForecastingRedesign,
}))(ShorttermForecastingRedesign);
